package cn.lyjuan.android.demofive.frame.tpl;

import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import cn.lyjuan.android.demofive.BR;

/**
 * RecyclerView适配器<br />
 * 通过{@code lf}将{@code itemLayoutId}填充到{@code RecyclerView}中，
 * 使用{@code viewModel}管理控件的数据及{@code onItemClick},{@code onItemLongClick}事件
 * Created by chad on 12/11/2017.
 */
public class TplRecyclerAdapter
        extends RecyclerView.Adapter<TplRecyclerAdapter.RecyclerViewHolder>
{
    /**
     * 视图模型
     */
    protected IListViewModel viewModel;

    /**
     * Item视图ID
     */
    protected int itemLayoutId;

    /**
     * 视图填充器
     */
    protected LayoutInflater lf;

    public TplRecyclerAdapter(IListViewModel viewModel, int itemLayoutId, LayoutInflater lf)
    {
        this.viewModel = viewModel;
        this.itemLayoutId = itemLayoutId;
        this.lf = lf;
    }

    @Override
    public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
    {
        LayoutInflater.from(parent.getContext());
        ViewDataBinding binding = DataBindingUtil.inflate(lf, itemLayoutId, parent, false);

        return new RecyclerViewHolder(binding, binding.getRoot());
    }

    @Override
    public void onBindViewHolder(RecyclerViewHolder holder, int position)
    {
        holder.getBinding().setVariable(BR.viewModel, viewModel);
        holder.getBinding().setVariable(BR.position, position);
    }

    @Override
    public int getItemCount()
    {
        return viewModel.getCount();
    }

    public IListViewModel getViewModel()
    {
        return viewModel;
    }

    public void setViewModel(IListViewModel viewModel)
    {
        this.viewModel = viewModel;
    }

    public int getItemLayoutId()
    {
        return itemLayoutId;
    }

    public void setItemLayoutId(int itemLayoutId)
    {
        this.itemLayoutId = itemLayoutId;
    }

    public LayoutInflater getLf()
    {
        return lf;
    }

    public void setLf(LayoutInflater lf)
    {
        this.lf = lf;
    }

    public class RecyclerViewHolder extends RecyclerView.ViewHolder
    {
        protected ViewDataBinding binding;

        public RecyclerViewHolder(ViewDataBinding binding, View itemView)
        {
            super(itemView);
            this.binding = binding;
        }

        public ViewDataBinding getBinding()
        {
            return binding;
        }
    }
}
